package anatex.kea.genex.extractor;

import java.util.*;
import org.annolab.tt4j.*;

import anatex.kea.genex.*;
import anatex.kea.*;

import java.text.*;

public class POSDetection {

	public static ArrayList<Object[]> tags;
	protected TreeTaggerWrapper tt;
	protected TokenHandler<String> th;
	
	public POSDetection() throws KeywordExtractorAlgoException  {
		//TODO fix with my install, + folder /model s files with parameters
		//TreeTagger Home on Server
		String treeTaggerHome = System.getProperty("treetagger.home");
		if(treeTaggerHome == null){
			treeTaggerHome = System.getenv("TreeTagger");
		}
		if(treeTaggerHome == null){
			String path = System.getenv("PATH");
			if(path == null){
				path = System.getenv("path");
			}
			if(path == null){
				path = System.getenv("Path");
			}
			
			//path delimiter depends on os type
			String pathDelimiter = "";
			if (path.contains(";")) {
				pathDelimiter = ";";
			} else {
				pathDelimiter = ":";
			}
			
			if( path.toLowerCase().contains("tree") && path.toLowerCase().contains("tagger")){
				do{
				  if(path.contains(pathDelimiter)){
					  treeTaggerHome = path.substring(0,path.indexOf(pathDelimiter.charAt(0)));
					  path = path.substring(path.indexOf(pathDelimiter.charAt(0)) + 1);
				  } else{
					  treeTaggerHome = path;
					  path = "";
				  }
				  
				}while(!(treeTaggerHome.toLowerCase().contains("tree") && treeTaggerHome.toLowerCase().contains("tagger")));
				
				if(treeTaggerHome.toLowerCase().endsWith("bin")){
					treeTaggerHome = treeTaggerHome.substring(0, treeTaggerHome.toLowerCase().lastIndexOf("bin")-1);
				} else if (treeTaggerHome.toLowerCase().endsWith("cmd")) {
					treeTaggerHome = treeTaggerHome.substring(0, treeTaggerHome.toLowerCase().lastIndexOf("cmd")-1);
				}
			}else{
				throw new KeywordExtractorAlgoException("TreeTagger not found in environment variables");
			}
		}
		System.setProperty("treetagger.home", treeTaggerHome);
		tags = new ArrayList<Object[]>();
		tt = new TreeTaggerWrapper<String>();
		th = new TokenHandler<String>() {
			public void token(String token, String pos, String lemma) {
				POSDetection.tags.add(new Object[] {token, pos});
			}
		};
		
		initTagger();
	}
	
	protected void initTagger() {
		Locale lc = GenEx.getCurrentLocale();
		String language = lc.getLanguage();
		
		try {
			if ("bg" == language) {
				tt.setModel("bulgarian.par:UTF-8");
			} else if ("en" == language) {
				tt.setModel("english.par:iso8859-1");
			}
			
			tt.setHandler(th);
		} catch (Exception ex) {
			//TODO Handle TreeTagger exception properly
			System.out.println(ex.getMessage());
		}
	}
	
	public ArrayList<Object[]> getTags(Collection words) {
		tags = new ArrayList<Object[]>();
		
		try {
			tt.process(words);
		} catch (Exception ex) {
			//TODO Handle TreeTagger exception properly
			System.out.println(ex.getMessage());
		}
		
		return tags;
	}
	
}
